const router = require('koa-router')()
const { models } = require('../../model')
const { convertToObjectId } = require('../../utils/db')
const { getTagByIds } = require('../../service/tool')
const { cloneDeep } = require('lodash')

const TOOL_PUBLIC_ATTRS = {
  name: 1,
  description: 1,
  statistics: 1,
  permalink: 1,
  icon: 1,
  tags: 1,
  background: 1
}

// 标签 - 获取所有 1/2/3 级标签
router.get('/tags', async function (ctx) {
  const tags = await models.ToolTag.find({
    level: {
      $in: [1, 2, 3]
    },
    status: 1
  }).project({
    source: 0,
    icon: 0
  }).sort({
    name: 1
  }).toArray()

  // 将 parentTags 数组解开来
  const unnestTags = []
  tags.forEach(tag => {
    if (tag.parentTags === 'undefined' || tag.parentTags.length === 0) {
      tag.parentTag = ''
      unnestTags.push(tag)
    } else {
      tag.parentTags.forEach(pt => {
        const tagTmp = cloneDeep(tag)
        tagTmp.parentTag = pt.toString()
        unnestTags.push(tagTmp)
      })
    }
  })
  // 转为树结构
  const array2Tree = (data, pid) => {
    const res = []
    data.forEach(item => {
      if (item.parentTag === pid) {
        const itemChildren = array2Tree(data, item._id.toString())
        if (itemChildren.length) item.children = itemChildren
        // q-menu不允许有相同的id，故生成新id，因为1个标签会有多个父标签
        // item.menuId = ++i
        res.push(item)
      }
    })
    return res
  }
  let tagsTree = array2Tree(unnestTags, '')
  // 对于Topic下标签的不返回
  tagsTree = tagsTree.filter(e => e.name !== 'Topic')

  ctx.wrapper.succ(tagsTree)
})

// 工具 - 根据标签、搜索关键字筛选
router.get('/tools', async function (ctx) {
  const query = ctx.query
  const findQuery = {}
  if (query.tags) {
    query.tags = _.isArray(query.tags) ? query.tags : [query.tags].filter(e => !!e)
    const queryTags = convertToObjectId(query.tags)
    const childTags = queryTags.length > 0
      ? await models.ToolTag.find({
        parentTags: {
          $elemMatch: { $in: queryTags }
        }
      }).project({
        _id: 1
      }).toArray()
      : []
    findQuery.tags = {
      $in: [
        ...queryTags,
        ...childTags.map(e => e._id)
      ]
    }
  }
  if (query.keywords) {
    findQuery.$or = [
      { name: { $regex: `${query.keywords}` } },
      { description: { $regex: `${query.keywords}` } },
      { permalink: { $regex: `${query.keywords}` } }
    ]
  }
  // query.sort
  if (query.sorts === undefined || query.sorts === '') {
    query.sorts = { updatedAt: -1 }
  } else {
    query.sorts = JSON.parse(query.sorts)
  }
  findQuery.status = 1
  const docs = await models.Tool
    .find(findQuery)
    .project(TOOL_PUBLIC_ATTRS)
    .sort(query.sorts)
    .limit(100)
    .toArray()
  // 补充标签信息
  for (const doc of docs) {
    doc.tags = await getTagByIds(doc.tags)
  }
  ctx.wrapper.succ(docs)
})

// 工具 - 根据 ID 获取一组工具
router.post('/tool/actions/getByIds',
  async function (ctx) {
    const ids = ctx.request.body.ids
    if (!ids || ids.length <= 0) {
      return ctx.wrapper.succ([])
    }
    const docs = await models.Tool.find({
      _id: { $in: convertToObjectId(ids) }
    }).project(TOOL_PUBLIC_ATTRS).toArray()
    // 补充标签信息
    for (const doc of docs) {
      doc.tags = await getTagByIds(doc.tags)
    }
    ctx.wrapper.succ(docs)
  }
)

const Topic = require('../../controller/topic')
const _ = require('lodash')
const topicController = new Topic()
router.post('/topic/actions/findAll', topicController.findAll())
router.post('/topic/actions/findPages', topicController.findPages())

module.exports = router
